package com.jwdf.uda.http.action;

import android.content.Context;
import android.os.Environment;
import com.jwdf.uda.bean.UploadListImageResponse;
import com.jwdf.uda.http.ApiFileUploadListService;
import com.jwdf.uda.http.ApiServiceModule;
import com.jwdf.uda.utils.FileUtils;
import com.jwdf.uda.utils.LogUtils;
import com.jwdf.uda.utils.NETUtils;
import com.jwdf.uda.utils.ToastUtils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 类说明：
 * 作者：huangqiuxin on 2016/5/23 11:01
 * 邮箱：648859026@qq.com
 */
public class UploadImageListsAction {
    private final static String TAG = UploadImageListsAction.class.getSimpleName();
    public final long UPLOAD_IMAGE_SIZE_LIMIT = 1024 * 1024;//1M

    protected Context context;
    protected ApiFileUploadListService apiFileUploadService;
    private String imagePath;
    private List<File> mListImagePath;
    private File uploadImageFile = null;

    public UploadImageListsAction(Context context, List<File> listImagePath , int i) {
        this.context = context;
        apiFileUploadService = ApiServiceModule.getInstance().providerApiFileUploadServices(context,i);
        this.mListImagePath = listImagePath;
    }




    public interface IResCallback<T> {
        int RESULT_OK = 0;

        int RESULT_NOT_NET_ERROR = 1;

        int RESULT_UPIMAGE_ERROR = 2;

        int RESULT_FILE_NOTEXIT_ERROR = 3;

        int RESULT_OTHER_ERROR = 4;

        void onCallback(int resultCode, UploadListImageResponse response);
    }

    /**
     * 发送请求数据
     *
     * @param iResCallback
     * @return
     */
    public Call request(final IResCallback<String> iResCallback) {
        if (!NETUtils.isNetworkConnected(context)) {
            //处理无网络情况
            if (iResCallback != null) {
                iResCallback.onCallback(IResCallback.RESULT_NOT_NET_ERROR, null);
            }
            return null;
        }
        final Map<String, RequestBody> photos = new HashMap<>();
        for(int i=0;i<mListImagePath.size();i++){
            if (mListImagePath.get(i) == null || !mListImagePath.get(i).exists()) {
                ToastUtils.show(context, "上传文件不存在！");
                iResCallback.onCallback(IResCallback.RESULT_FILE_NOTEXIT_ERROR, null);
                return null;
            }


            photos.put("upload_picture_"+(i+1)+"\"; filename=\"" + mListImagePath.get(i).getName(), RequestBody.create(MediaType.parse("multipart/form-data"), mListImagePath.get(i)));

        }

        Call<UploadListImageResponse> call = apiFileUploadService.uploadImages(photos);
        enqueue(call, iResCallback);
        return call;
    }

    private void enqueue(Call<UploadListImageResponse> call, final IResCallback<String> iResCallback) {
        call.enqueue(new Callback<UploadListImageResponse>() {
            @Override
            public void onResponse(Call<UploadListImageResponse> call, Response<UploadListImageResponse> response) {
                LogUtils.i(TAG, "onResponse");
                int responseCode = response.code();
                if (responseCode == 200) {
                    if (iResCallback != null) {
                        iResCallback.onCallback(IResCallback.RESULT_OK, response.body());
                    }
                } else {
                    try {
                        String msg = new String(response.errorBody().bytes());
                        LogUtils.i(TAG, "onResponse responseCode:" + responseCode + "," + msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (iResCallback != null) {
                        iResCallback.onCallback(IResCallback.RESULT_UPIMAGE_ERROR, null);
                    }
                }
                delUploadImageFile();
            }

            @Override
            public void onFailure(Call<UploadListImageResponse> call, Throwable t) {
                LogUtils.i(TAG, "onFailure:");
                t.printStackTrace();
                if (iResCallback != null) {
                    iResCallback.onCallback(IResCallback.RESULT_UPIMAGE_ERROR, null);
                }
                delUploadImageFile();
            }
        });
    }

    private static File createTempImageFile(String imageType) throws IOException {
        // Create an image file name
        String imageFileName = "temp"+UUID.randomUUID();
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        if (!storageDir.exists()) {
            if (!storageDir.mkdir()) {
                throw new IOException();
            }
        }
        File image = new File(storageDir, imageFileName + imageType);
        return image;
    }

    private synchronized static String getImageType(String uri) {
        String[] array = uri.split("\\.");
        return "." + array[array.length - 1].toLowerCase();
    }

    private void delUploadImageFile() {
        if (uploadImageFile != null) {
            FileUtils.deleteTempFile(uploadImageFile.getAbsolutePath());
            uploadImageFile = null;
        }
    }

}
